/* 
 * 功能：按键防抖、节流处理
 */

// 防抖（立即执行）
export function debounce(Vue) {
    const on = Vue.prototype.$on
    Vue.prototype.$on = function (event, func) {
        let timer;
        let flag = true;
        let newFunc = func
        if (event === 'click') {
            newFunc = function () {
                if (timer) {
                    clearTimeout(timer);
                    timer = null;
                }
                if (flag) {
                    func.apply(this, arguments);
                    flag = false;
                }
                timer = setTimeout(function () {
                    flag = true;
                    timer = null;
                }, 100)
            }
        }
        on.call(this, event, newFunc)
    }
}
// 防抖(非立即执行)
export function debounceEx(Vue) {
    const on = Vue.prototype.$on
    Vue.prototype.$on = function (event, func) {
        let timer
        let newFunc = func
        if (event === 'click') {
            newFunc = function () {
                clearTimeout(timer)
                timer = setTimeout(function () {
                    func.apply(this, arguments)
                }, 500)
            }
        }
        on.call(this, event, newFunc)
    }
}
// 节流
export function throttle(Vue) {
    const on = Vue.prototype.$on
    Vue.prototype.$on = function (event, func) {
        let previous = 0
        let newFunc = func
        if (event === 'click') {
            newFunc = function () {
                const now = new Date().getTime()
                if (previous + 1000 <= now) {
                    func.apply(this, arguments)
                    previous = now
                }
            }
        }
        on.call(this, event, newFunc)
    }
}
